import { createVNode } from 'vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import * as XLSX from 'xlsx/xlsx.mjs';

function getTree(data: any[], root: string, idTxt: string, pidTxt: string, pushTxt: string) {
    var idTxt = idTxt || 'id';
    var pidTxt = pidTxt || 'pid';
    var pushTxt = pushTxt || 'children';
    // 递归方法
    function getNode(id) {
        var node: any[] = [];
        for (var i = 0; i < data.length; i++) {
            if (data[i][pidTxt] == id) {
                data[i][pushTxt] = getNode(data[i][idTxt]);
                node.push(data[i]);
            }
        }
        if (node.length == 0) {
            return;
        } else {
            return node;
        }
    }
    // 使用根节点
    return getNode(root);
}

// data --> tree
export const toTreeData = (dataArr: any) => {
    let dataObjById = {};
    dataArr.map((item: any) => {
        dataObjById[item['code']] = item;
    });
    let result: any = [];
    dataArr.map((item: any) => {
        var parentNode = dataObjById[item['parent_code']];
        if (parentNode) {
            if (!parentNode['children']) {
                parentNode['children'] = [];
            }

            parentNode['children'].push(item);
            let map = new Map();
            for (let item of parentNode['children']) {
                map.set(item.id, item);
            }
            parentNode['children'] = [...map.values()];

            let childrenArr = parentNode['children'];
            childrenArr.map((item2) => {
                if (!item2.children) {
                    item2.children = [];
                    let { id, name, code, parent_code } = parentNode;
                    item2.parent = { id, name, code, parent_code };
                }
            });
            if (dataObjById[parentNode['parent_code']]) {
                let { id, name, code, parent_code } = dataObjById[parentNode['parent_code']];
                parentNode.parent = { id, name, code, parent_code };
            } else {
                parentNode.parent = {};
            }
        } else {
            result.push(item);
        }
    });
    result.map((item3) => {
        if (!item3.children) {
            item3.children = [];
            item3.parent = {};
        }
    });
    return [...result];
};

// 金额千分位，区分正负
export const toThousands = (str) => {
    // 判断正负
    str = str - 0;
    let fu = false;
    if (str < 0) {
        str = 0 - str;
        fu = true;
    }

    //含小数每3位分隔
    var newStr = '';
    var count = 0;
    str = str + '';
    // 当数字是整数
    if (str.indexOf('.') == -1) {
        for (var i = str.length - 1; i >= 0; i--) {
            if (count % 3 == 0 && count != 0) {
                newStr = str.charAt(i) + ',' + newStr;
            } else {
                newStr = str.charAt(i) + newStr;
            }
            count++;
        }
        str = newStr;
        // str = newStr + ".00"; //自动补小数点后两位
        if (fu) {
            str = '-' + str;
        }
        return str;
    }
    // 当数字带有小数
    else {
        for (let i = str.indexOf('.') - 1; i >= 0; i--) {
            if (count % 3 == 0 && count != 0) {
                newStr = str.charAt(i) + ',' + newStr;
            } else {
                newStr = str.charAt(i) + newStr; //逐个字符相接起来
            }
            count++;
        }
        str = newStr + (str + '00').substr((str + '00').indexOf('.'), 3);
        if (fu) {
            str = '-' + str;
        }
        return str;
    }
};

// 导出excel
const transData = (columns, tableList) => {
    const obj = columns.reduce((acc, cur) => {
        if (!acc.titles && !acc.keys) {
            acc.titles = [];
            acc.keys = [];
        }
        acc.titles.push(cur.title);
        acc.keys.push(cur.dataIndex);
        return acc;
    }, {});
    const tableBody = tableList.map((item) => {
        return obj.keys.map((key) => item[key]);
    });
    return [obj.titles, ...tableBody];
};

export const exportExcel = (dataSource, columns, fileName) => {
    if (dataSource.length == 0) {
        message.warning('没有数据可以导出！');
        return;
    }
    Modal.confirm({
        title: `确认导出${dataSource.length}条数据吗?`,
        icon: createVNode(ExclamationCircleOutlined),
        onOk() {
            const tableData = transData(columns, dataSource);
            // 将一组 JS 数据数组转换为工作表
            const ws = XLSX.utils.aoa_to_sheet(tableData);
            // 创建 workbook
            const wb = XLSX.utils.book_new();
            // 将 工作表 添加到 workbook
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet');
            // 将 workbook 写入文件
            XLSX.writeFile(wb, fileName);
        },
        onCancel() {},
        class: 'test',
    });
};